<script lang="ts" setup>
import { computed, useSlots, useAttrs } from "vue";

defineOptions({ name: "Drawer" });

export interface DrawerProps {
  modelValue?: boolean;
  title?: string;
  direction?: "rtl" | "ltr" | "ttb" | "btt";
  size?: string | number;
  appendToBody?: boolean;
  closeOnClickModal?: boolean;
  beforeClose?: (done: () => void) => void;
}

const props = withDefaults(defineProps<DrawerProps>(), {
  modelValue: false,
  title: "Drawer",
  direction: "rtl",
  size: "400px",
  appendToBody: true,
  closeOnClickModal: false,
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "close"): void;
}>();

const slots = useSlots();

const getBindValue = computed(() => {
  const delArr: string[] = ["title"];
  const attrs = useAttrs();
  const obj: Record<string, any> = { ...attrs, ...props };
  for (const key in obj) {
    if (delArr.indexOf(key) !== -1) {
      delete obj[key];
    }
  }
  return obj;
});

const handleClose = () => {
  emit("update:modelValue", false);
  emit("close");
};
</script>

<template>
  <ElDrawer
    v-bind="getBindValue"
    :model-value="modelValue"
    :title="title"
    :close-on-click-modal="closeOnClickModal"
    :append-to-body="appendToBody"
    @update:model-value="(val) => emit('update:modelValue', val)"
    @close="handleClose"
    class="com-drawer"
  >
    <template #header="{ titleId, titleClass }">
      <div class="com-drawer-header">
        <slot name="title">
          <span :id="titleId" :class="titleClass">{{ title }}</span>
        </slot>
        <div class="com-drawer-header-actions">
          <span
            class="com-drawer-header-action i-ri-close-line"
            @click="handleClose"
          ></span>
        </div>
      </div>
    </template>

    <slot></slot>

    <template v-if="slots.footer" #footer>
      <slot name="footer"></slot>
    </template>
  </ElDrawer>
</template>

<style lang="scss">
@use "./Drawer.scss";
</style>

